﻿using RpcCacheClient.Interface;
using RpcClient;
using RpcHelper;
using RpcSync.Collect.linq;
using RpcSync.Collect.Model;
using RpcSync.DAL;
using RpcSync.Model;

namespace RpcSync.Collect.Collect
{
    internal class SysConfigCollect : ISysConfigCollect
    {
        private ISysConfigDAL _SysConfigDAL;
        private ICacheController _Cache;
        public SysConfigCollect(ISysConfigDAL configDAL,
            ICacheController cache)
        {
            this._Cache = cache;
            this._SysConfigDAL = configDAL;
        }

        public SysConfigItem GetSysConfig(string type)
        {
            string key = "SysConfig_" + (type.IsNull() ? "public" : type);
            if (this._Cache.IsEnable && this._Cache.TryGet(key, out SysConfigItem item))
            {
                return item;
            }
            SysConfig[] configs = this._SysConfigDAL.GetSysConfig(type).OrderByDescending(a => a.ToUpdateTime).ToArray();
            if (configs == null)
            {
                configs = new SysConfig[0];
            }
            item = new SysConfigItem
            {
                Items = configs.ConvertMap<SysConfig, ConfigItem>((a, b) => {
                    b.InitConfig();
                    return b;
                }),
                Md5 = configs.GetConfigMd5()
            };
            if (this._Cache.IsEnable)
            {
                this._Cache.Set(key, item, new TimeSpan(Tools.GetRandom(1, 30), 0, 0, 0));
            }
            return item;
        }

        public Dictionary<string, DateTime> GetToUpdateTime()
        {
            return this._SysConfigDAL.GetToUpdateTime();
        }

        public SysConfigItem Refresh(string type)
        {
            string key = "SysConfig_" + type;
            this._Cache.Remove(key);
            return GetSysConfig(type);
        }
    }
}
